<!DOCTYPE html>
<head>
    <meta charset="utf-8">
    <h1 style="text-align: center;">抽到就是赚到，我运气也太好了吧</h1>

    <script src="https://libs.baidu.com/jquery/1.10.2/jquery.min.js"></script>
    <link rel="stylesheet" href="styles.css">
</head>
    
<body>

    <div class="container">
        <div class="config">
            <h2>配置</h2>
            <div class="info">人员名单文件</div>
            <!-- <input type="file" id="file-input" accept=".csv" /> -->
            
            <div class="file-container">
                <label for="file-input" class="custom-file-input">选择文件</label>
                <input type="file" id="file-input" accept=".txt, .csv" />
                <p id="fileInfo" class="file-info">未选择任何文件</p>
            </div>
            
            <div class="info">抽选停止方式</div>
            <div class="option-group">
                <input type="radio" id="manual-stop" name="options" value="manual" checked>
                <label for="manual-stop">手动停止</label>

                <input type="radio" id="auto-stop" name="options" value="auto">
                <label for="auto-stop">自动停止</label>
            </div>
        </div>

        <div class="display">
            <span class="disp-names-panel">
                <h2>人员名单</h2>
            </span>
            <span class="disp-selected-panel">
                <h2>中奖名单</h2>
                <div class="selected-name-panel"></div>
            </span>
        </div>
        
    </div>

    <div class="bottom-area">
        <button id="start-button">开始</button>
    </div>

   
    <script>
        nameList = undefined;
        selectedIdx = 0;

        // 监听文件按钮事件
        document.getElementById('file-input').addEventListener('change', function(event) {
            clearNamesList(); // 避免多次选择文件时遗留前一个文件想内容
            const file = event.target.files[0];
            if (file) {
                fileInfo.textContent = `${file.name}`;

                const reader = new FileReader();
                reader.onload = function(e) {
                    let result = e.target.result;
                    const lines = result.split('\n').map(line => line.trim());
                    nameList = lines.map(line => line.split(',').map(item => item.trim()));

                    // 根据文本内容初始化人员名单窗口
                    init();
                };
                reader.readAsText(file);                
            } else {
                fileInfo.textContent = '未选择任何文件';
            }
        });

        // 监听开始按钮事件
        $('#start-button').click(function() {       
            // 每次点击按钮都清理中奖区域内容 
            clearSelectedBox();

            if (nameList === undefined) {
                alert("请先导入人员名单");
                return;
            }

            let manualOpt = document.getElementById("manual-stop");
            let interval = 50;
            if (manualOpt.checked) {
                // 选中手动停止选项的情况
                if (this.innerText === "开始") {
                    tid = setInterval(function(){
                    resetNameBoxColor();

                    selectedIdx = Math.floor(Math.random() * nameList.length);
                    setNameBoxColor(selectedIdx);
                    }, interval);
                    // this.value = "停止";
                    // this.innerHTML = "停止";
                    this.innerText = "停止";
                } else {
                    clearInterval(tid);
                    addSelectedBox(selectedIdx);
                    this.innerText = "开始";
                }
                
            } else {
                // 选中自动停止选项的情况
                // @TODO 当当前抽奖过程未完成前重复点击开始按钮时，会导致多个抽选结果的情况
                let max = 50;
                let numLoop = Math.floor(Math.random() * max); // 设置随机的循环次数
                let loop = 0;
                let tid = setInterval(function(){
                    resetNameBoxColor(); // 将姓名框填充颜色重置
                    selectedIdx = Math.floor(Math.random() * nameList.length);
                    setNameBoxColor(selectedIdx); // 填充姓名框颜色
                    
                    loop++;
                    if (loop >= numLoop) {
                        // 清理定时器，并将选中的人员添加到中奖显示区域
                        clearInterval(tid);
                        addSelectedBox(selectedIdx);
                    }
                }, interval);
            }
                
        })


        // 根据文件信息初始化人员名单显示区域内容
        function init() {          
            // 动态设置单元格高度
            let nums = nameList.length;
            let cellHeigh = nums / 3 * 40 + 120;

            createNamesTable(nameList);
        }

        // 在人员名单区域添加姓名框表
        function createNamesTable(names) {
            if (names.length === 0) {
                alert("输入文件内容为空！");
                return;
            }
            for(let i = 0; i < names.length; ++i) {
                let div = document.createElement("div");
                div.innerText = names[i];
                div.className = "name-box";
                $(".disp-names-panel").append(div)
            }
        }

        // 设置人员名单显示区域姓名框的填充色
        function setNameBoxColor(idx) {
            $(".disp-names-panel").children("div").each(function() {
                let text = ($(this).text());
                let name = nameList[idx];

                if (text == name) {
                    $(this).css("background-color", "red");
                }
            });
        }

        // 重置人员名单显示区域姓名框的填充色
        function resetNameBoxColor() {
            $(".disp-names-panel").children("div").each(function() {
                $(this).css("background-color", "");
            });
        }
        
        // 将中奖人员添加到中奖区域
        function addSelectedBox(idx) {
            let div = document.createElement("div");
            div.innerText = nameList[idx];
            div.className = "selected-box";
            $(".selected-name-panel").append(div);
        }

        // 清理人员名单区域信息
        function clearNamesList() {
            nameList = undefined;
            const elem = document.querySelectorAll(".name-box");
            elem.forEach(elem=>{
                elem.remove();
            });
            
        }

        // 清理中奖区域信息
        function clearSelectedBox() {
            const elem = document.querySelectorAll(".selected-box");
            elem.forEach(elem=>{
                elem.remove();
            });
        }

    </script>
</body>